﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data;

namespace SDL
{
    public class SDLDbConnection
    {
        public delegate void dOnFree(SDLDbConnection connection);

        public event dOnFree OnFree;

        public bool Locked { get; private set; }

        public bool Dirty { get; set; }

        public DbConnection Connection { get; private set; }

        public DbDataReader Reader { get; set; }

        public int Index { get; set; }

        public ConnectionString ConnectionString
        {
            get { return Connection.ConnectionString.ToConnection(); }
            set { Connection.ConnectionString = value.ToString(); }
        }

        public SDLDbConnection(DbConnection connection)
        {
            Connection = connection;
        }

        public ConnectionState State
        {
            get { return Connection.State; }
        }

        public void Open()
        {
            Connection.Open();
        }

        public void Close()
        {
            Connection.Close();
        }

        public DbCommand CreateCommand()
        {
            Busy();
            return Connection.CreateCommand();
        }

        public void Free()
        {
            Locked = false;
            if (Reader != null && !Reader.IsClosed) Reader.Close();
            if (OnFree != null) OnFree(this);
        }

        public void Busy()
        {
            Locked = true;
        }
    }
}
